﻿using SportsPlatform.Base;
using SqlSugar;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SportsPlatform.Helpers;
using System;
using SportsPlatform.Consts;
using Abp.ObjectMapping;
using SportsPlatform.SportBusiness.ISportBusiness;
using SportsPlatform.Dto.SportBusiness.Employee;
using SportsPlatform.Query.SportBusiness.Employee;
using SportsPlatform.Model.SportBusiness;
using Abp.Application.Services;
using Abp.Domain.Repositories;
using SportsPlatform.Query.SportBusiness.Team;
using SportsPlatform.Query.SportBusiness.CompetitionAchievementInfo;
using SportsPlatform.Dto.SportBusiness.Category;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using static NPOI.HSSF.Util.HSSFColor;
using static iTextSharp.text.pdf.AcroFields;
using NPOI.SS.Formula.Functions;
using Microsoft.AspNetCore.Http;
using SportsPlatform.Global;

namespace SportsPlatform.SportBusiness.SportBusiness
{
    /// <summary>
    /// 用户管理服务
    /// </summary>
    [RemoteService(false)]  //隐藏自动生成的WebApi
    public class EmployeeService : SportsPlatformAppServiceBase, IEmployeeService
    {
        private readonly IRepository<Employee, Guid> _repository;
        private readonly IRepository<Team, Guid> _teamRpository;
        private readonly IRepository<TeamUser, Guid> _teamUserRpository;
        private readonly IHttpContextAccessor _context;
        public EmployeeService(IRepository<Employee, Guid> repository, IRepository<Team, Guid> teamRpository,
            IRepository<TeamUser, Guid> teamUserRpository, IHttpContextAccessor context) : base(context)
        {
            _repository = repository;
            _teamRpository = teamRpository;
            _teamUserRpository = teamUserRpository;
            _context = context;
        }


        /// <summary>
        /// 获取分页后的用户数据
        /// </summary>
        /// <param name="pageQuery">查询条件</param>
        /// <returns></returns>
        public async Task<PagePagingDto<EmployeeDto>> GetPagePagingDto(GetEmployeeQuery pageQuery)
        {
            PagePagingDto<EmployeeDto> result = new PagePagingDto<EmployeeDto>();
            var asyncres = await _repository.GetAllListAsync(a => a.IsDeleted == false);
            if (asyncres.Count > 0)
            {
                //获取总条数
                var rescount = asyncres.WhereIF(!pageQuery.NameAndPhone.IsNullAndEmpty(),
                    c => c.RealName.Contains(pageQuery.NameAndPhone) ||
                    c.Phone.Contains(pageQuery.NameAndPhone)).ToList();
                //获取分页数据
                var res = asyncres.WhereIF(!pageQuery.NameAndPhone.IsNullAndEmpty(),
                    c => c.RealName.Contains(pageQuery.NameAndPhone) ||
                    c.Phone.Contains(pageQuery.NameAndPhone))
                          .Skip(pageQuery.PageSize * (pageQuery.PageIndex - 1))
                          .Take(pageQuery.PageSize)
                          .ToList();
                List<EmployeeDto> dtos = new List<EmployeeDto>();
                var teamUsers = await _teamUserRpository.GetAllListAsync();
                var teams = await _teamRpository.GetAllListAsync();
                foreach (var item in res)
                {
                    if (item.IDNumber.IsNullAndEmpty() || item.Phone.IsNullAndEmpty())
                    {
                        throw new UldAdminCustomException("服务器内部错误");
                    }

                    var employee = new EmployeeDto
                    {
                        IDNumber = item.IDNumber.Substring(0, 6) + "****" + item.IDNumber.Substring(item.IDNumber.Length - 4, 4),
                        HeadPortrait = item.HeadPortrait,
                        NickName = item.NickName,
                        Phone = item.Phone.Substring(0, 3) + "****" + item.Phone.Substring(item.Phone.Length - 4, 4),
                        RealName = item.RealName,
                        RegisterTime = item.RegisterTime.ToString("yyyy-MM-dd"),
                        Sensor = item.Sensor,
                        Sex = item.Sex,
                        Id = item.Id,
                    };
                    teamUsers = teamUsers.Where(t => t.EmployeeId == item.Id).ToList();
                    if (teamUsers.Count > 0)
                    {
                        foreach (var teamUser in teamUsers)
                        {
                            var team = teams.FirstOrDefault(t => t.Id == teamUser.TeamId);
                            employee.TeamName += team.TeamName + ",";
                            employee.TeamId = team.Id;
                        }
                        employee.TeamName = employee.TeamName.Substring(0, employee.TeamName.Length - 1);
                    }

                    dtos.Add(employee);

                }

                result.TotalCount = rescount.Count;
                result.Code = HttpResultCode.Success;
                result.IsSuccess = true;
                result.Message = "查询成功";
                result.Data = dtos;
                return result;
            }
            else
            {
                result.Code = HttpResultCode.SqlError;
                result.Message = "未查询到数据";
                return result;
            }


            return result;
        }

        /// <summary>
        /// 添加成员
        /// </summary>
        /// <param name="Query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> AddTeamUser(AddEmployeeQuery Query)
        {
            try
            {
                #region 比赛规则信息
                Employee info = ObjectMapper.Map<Employee>(Query);
                info.CreateTime = DateTime.Now;
                info.CreateUserId = Guid.Empty;
                if (Query.IDNumber.GetSex() == "男")
                {
                    info.Sex = 1;
                }
                else
                {
                    info.Sex = 0;
                }
                info.RegisterTime = DateTime.Now;
                #endregion

                var team = await _teamRpository.GetAsync(Query.TeamId);
                if (team != null)
                {
                    var employee = await _repository.FirstOrDefaultAsync(e => e.IDNumber.Contains(Query.IDNumber));
                    if (employee != null)
                    {
                        var teameUser = await _teamUserRpository.InsertAsync(new TeamUser
                        {
                            EmployeeId = employee.Id,
                            TeamId = team.Id,
                        });
                    }
                    else
                    {
                        var guidId = await _repository.InsertAndGetIdAsync(info);
                        var teameUser = await _teamUserRpository.InsertAsync(new TeamUser
                        {
                            EmployeeId = guidId,
                            TeamId = team.Id,
                        });
                    }
                    team.TeamNum += 1;
                    team.UpdateTime = DateTime.Now;
                    await _teamRpository.UpdateAsync(team);

                    return new BaseResultDto()
                    {
                        IsSuccess = true,
                        Code = (int)HttpResultCode.Success,
                        Message = "保存成功"
                    };
                }
                else
                {
                    return new BaseResultDto()
                    {
                        Code = HttpResultCode.NotData,
                        Message = "未查询到该团队"
                    };
                }
            }
            catch (Exception ex)
            {
                return new BaseResultDto()
                {
                    IsSuccess = false,
                    Code = (int)HttpResultCode.Error,
                    Message = ex.Message
                };
            }
        }
    }
}
